package xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ParseXML {
	public Document document;
	// 获得DOM树
	public void getDomTree(){
		// 创建解析器工厂对象
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			// 通过解析器工程对象创建解析器对象
			DocumentBuilder db = factory.newDocumentBuilder();
			// 解析器对象指定XML文件创建Document对象
			document = db.parse("src/xml/新手机信息.xml");
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	  
	//解析 手机信息.xml，获得手机品牌和型号
	public void showInfo(){
		// 以Document对象为起点操作DOM树
		NodeList brands = document.getElementsByTagName("Brand");
		// 遍历NodeList,取出各节点
		for (int i = 0; i < brands.getLength(); i++) {
			Node brandNode = brands.item(i);
			Element eleBrand = (Element)brandNode;
			String brandName = eleBrand.getAttribute("name");
			System.out.println(brandName);
			// 继续找<Brand>品牌下面的节点<Type>型号
			NodeList types = eleBrand.getChildNodes();
			for (int j = 0; j < types.getLength(); j++) {
				Node typeNode = types.item(j);
				if(typeNode.getNodeType() == Node.ELEMENT_NODE){
					Element eleType = (Element)typeNode;
					String typeName = eleType.getAttribute("name");
					System.out.println("\t" + typeName);
				}
			}
		}
	}
	
	// 另存xml文件
	public void saveXML(String path){
		// 创建转换器工厂
		TransformerFactory factory = TransformerFactory.newInstance();
		// 设置缩进
		factory.setAttribute("indent-number", 4);
		try {
			// 获得转换器
			Transformer transformer = factory.newTransformer();
			// 指定特定的转换格式
			transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
			// 开启缩进
			transformer.setOutputProperty(OutputKeys.INDENT,"yes");
			// 源
			DOMSource source = new DOMSource(document);
			// 目标
//			StreamResult result = new StreamResult(new FileOutputStream(path));
			StreamResult result = new StreamResult(new OutputStreamWriter(new FileOutputStream(path), "GB2312"));
			// 转换
			transformer.transform(source, result);
			
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}
	
	// 为XML文件添加元素
	public void addEle(){
		// 创建Brand元素
		Element brand = document.createElement("Brand");
		// 设置Brand元素的name="三星"
		brand.setAttribute("name", "三星");
		// 创建Type元素
		Element type = document.createElement("Type");
		// 设置Type元素的name="note4"
		type.setAttribute("name","note4");
		// 把Type加到Brand里面去
		brand.appendChild(type);
		// 再把Brand加到PhoneInfo里面去
		document.getElementsByTagName("PhoneInfo").item(0).appendChild(brand);
		saveXML("src/xml/手机信息.xml");
	}
	
	//修改元素:为每一个Brand元素添加id属性，属性值为0、1、2...
	public void modifyEle(){
		// 获得所有Brand元素
		NodeList brands = document.getElementsByTagName("Brand");
		for (int i = 0; i < brands.getLength(); i++) {
			Node brand = brands.item(i);
			Element brandEle = (Element)brand;
			// 为每一个Brand元素添加属性id
			brandEle.setAttribute("id", "" + i);
		}
		saveXML("src/xml/手机信息.xml");
	}
	
	// 删除元素：删除手机品牌为华为的相关元素
	public void deleteEle(){
		// 获得所有Brand元素
		NodeList brands = document.getElementsByTagName("Brand");
		for (int i = 0; i < brands.getLength(); i++) {
			Node brand = brands.item(i);
			Element brandEle = (Element)brand;
			// 找到Brand元素的属性name="华为"的元素,将其删除
			if(brandEle.getAttribute("name").equals("华为")){
				brandEle.getParentNode().removeChild(brandEle);
			}
		}
		saveXML("src/xml/新手机信息.xml");
	}
	
	
	public static void main(String[] args) {
		ParseXML parseXML = new ParseXML();
		parseXML.getDomTree();
		//parseXML.showInfo();
		//parseXML.saveXML("src/xml/新手机信息.xml");
		//parseXML.addEle();
		//parseXML.modifyEle();
		parseXML.deleteEle();
	}
}
